﻿using System;
using System.ComponentModel;
using System.Windows.Input;
#if (WINRT)
using Windows.UI.Xaml;
#endif

namespace nRoute.Components
{
    public class CommandRelay 
		 : ICommand, INotifyPropertyChanged
    {
        ICommand _value;

        public event System.EventHandler<ValueEventArgs<ICommand>> Initialize;

        public ICommand Command
        {
            get { return _value; }
            set 
            {
//#if (WINRT)
//                // remove the old and add new - note to check if this can cause mem leaks
//                if (_value != null) _value.CanExecuteChanged -= OnCanExecuteChanged;
//                if (value != null) value.CanExecuteChanged += OnCanExecuteChanged;
//#endif
                _value = value;
                PropertyChanged.Notify(() => Command);
            }
        }

#region ICommand Members

        bool ICommand.CanExecute(object parameter)
        {
            if (_value == null && !InitializeCommand()) return false;
            return _value.CanExecute(parameter);
        }
        
//#if (!WINRT)
//        event EventHandler ICommand.CanExecuteChanged
//        {
//            add { if (_value != null || InitializeCommand()) _value.CanExecuteChanged += value; }
//            remove { if (_value != null || InitializeCommand()) _value.CanExecuteChanged -= value; }
//        }
//#else
        public event EventHandler CanExecuteChanged;
//#endif

        void ICommand.Execute(object parameter)
        {
            if (_value != null || InitializeCommand()) _value.Execute(parameter);
        }

#endregion

#region INotifyPropertyChanged Related

        public event PropertyChangedEventHandler PropertyChanged;

#endregion

#region Helper

        private bool InitializeCommand()
        {
            if (Command != null) return true;
            if (Initialize != null)
            {
                var _eventArgs = new ValueEventArgs<ICommand>();
                Initialize(this, _eventArgs);
                Command = _eventArgs.Value;
            }
            return (this.Command != null);
        }

//#if (WINRT)

//        private void OnCanExecuteChanged(object sender, object e)
//        {
//            if (this.CanExecuteChanged != null) this.CanExecuteChanged(this, e);
//        }

//#endif

#endregion

    }
}
